//
//  ZqlAccountVM.swift
//  ZqlSinaWeiBo
//
//  Created by 赵乾龙 on 16/2/19.
//  Copyright © 2016年 Mr.zhao. All rights reserved.
//

import UIKit
import AFNetworking

class ZqlAccountVM: NSObject {
    
    //定义单例
    static let shardAccountVM:ZqlAccountVM = ZqlAccountVM()
    
    //定义用户账户属性
    var userAccount:ZqlUsetAccount?
    
    private  override init() {
        super.init()
        userAccount = ZqlUsetAccount.loadUserAccount()
    }
    
    //用户是否登录的属性
    var userLogin:Bool{
        return userAccount?.access_token != nil
    }
    
    var access_token: String?{
        return userAccount?.access_token
    }
    //用户名的只读属性
    var userName:String?{
        return userAccount?.name
    }
    
    //用户头像的属性
    var headImageUrl:NSURL?{
        if let urlString = userAccount?.avatar_large{
            return NSURL(string: urlString)
        }
        
        return nil
    }
    
    //加载用户的token
    func loadAccessToken(code:String,finished:(isSuccess:Bool) ->()){
        //使用afn发起网络请求
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let afn = AFHTTPSessionManager()
        
        //设置afn的解析格式
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        //发起网络请求
        ZqlHTTPClient.sharedClient.requestJsonDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil{
                finished(isSuccess: false)
                return
            }
            let account = ZqlUsetAccount(dict: dict!)
            //获取用户信息
            self.loadUserInfo(account,finished: finished)
        }
    }
    
    //请求用户信息
    private func loadUserInfo(userAccount:ZqlUsetAccount,finished:(isSuccess:Bool) ->()){
        //用户信息借口url
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = ["access_token":userAccount.access_token!,"uid":userAccount.uid!]
        ZqlHTTPClient.sharedClient.requestJsonDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil{
                finished(isSuccess: false)
                return
            }
            // 用户名
            let name = dict!["name"] as! String
            //用户头像
            let avatar_large = dict!["avatar_large"] as! String
            
            userAccount.name = name
            userAccount.avatar_large = avatar_large
            
            //调用归档方法   保存用户信息
            userAccount.saveAccount()
            
            //给单例对象的模型属性赋值
            self.userAccount = userAccount
            
            //执行成功
            finished(isSuccess: true)
            
        }
    }
}
